import React, { Component } from 'react'
import { inject, observer } from 'mobx-react/index'
import { Form, Button, Card, Checkbox, message, Spin } from 'antd'
import { address } from '@/Utils/apiConfig'
import getData from '@/Utils/fecth'
import './joinChannel.less'
const { leagueManagement: { getPeerOfAddOrg, addPeerToChannel, getPeerOfInviteOrg, invitePeerToChannel }} = address

const FormItem = Form.Item
const CheckboxGroup = Checkbox.Group

@inject('SocketModel')
@observer
class JoinChannel extends Component {
  constructor(props) {
    super(props)
    this.state = {
      checkedList: [],
      indeterminate: false,
      checkAll: false,
      initialValues: {
        options: [],
      },
      loading: false,
      orgList: [],
      orgIds: [],
      channelName: props.match.params.channelName,
      channelId: props.match.params.channelId,
      consortiumId: props.match.params.id,
      type: props.match.params.type,
    }
    this.orgList = []
  }

		formRef = React.createRef();

		componentDidMount() {
		  this.getPeerOfChannel()
		}

		getPeerOfChannel = async() => {
		  const { consortiumId, channelId, type } = this.state
		  let orgList = null
		  let orgIds = null
		  const getPeer = () => {
		    return type === 'APPLY'
		      ? getPeerOfAddOrg
		      : getPeerOfInviteOrg
		  }
		  await getData().get(getPeer().format({ consortiumId, channelId })).then(res => {
		    switch (res.status) {
		    case 200:
		      orgList = res.data
		      orgIds = orgList.map(item => { return item.id })
		      this.setState({
		        orgList,
		        orgIds,
		        loading: false,
		      })
		      break
		    default:
		      message.error('请求失败')
		      break
		    }
		  })
		  return orgList
		}

		onChange = checkedList => {
		  this.setState({
		    checkedList,
		    indeterminate: !!checkedList.length && checkedList.length < this.state.orgIds.length,
		    checkAll: checkedList.length === this.state.orgIds.length,
		  })
		};

		onCheckAllChange = e => {
		  this.formRef.current.setFieldsValue({
		    options: e.target.checked ? this.state.orgIds : [],
		  })
		  this.setState({
		    checkedList: e.target.checked ? this.state.orgIds : [],
		    indeterminate: false,
		    checkAll: e.target.checked,
		  })
		};

		onFinish = async(values) => {
		  const { checkedList, consortiumId, channelId, type } = this.state
		  let params = {
		    orgIds: checkedList,
		  }
		  this.setState({
		    loading: true,
		  })
		  const submitOrgs = () => {
		    return type === 'APPLY'
		      ? addPeerToChannel.format({ consortiumId, channelId })
		      : invitePeerToChannel.format({ consortiumId, channelId })
		  }
		  let res = await getData().post(submitOrgs(), params)
		  this.setState({
		    loading: false,
		  })
		  if (res && res.status === 200) {
		    message.success(`${type === 'APPLY' ? '申请成功，等待投票' : '邀请成功'}`)
		    this.props.history.goBack()
		  } else {
		    message.error(`${type === 'APPLY' ? '添加失败' : '邀请失败'}`)
		  }
		}

		renderForm = () => {
		  const { initialValues, orgList } = this.state
		  const layout = {
		    labelCol: { span: 2 },
		    wrapperCol: { span: 10 },
		  }
		  const tailLayout = {
		    wrapperCol: { offset: 2, span: 10 },
		  }
		  return (
		    <Form ref={this.formRef} initialValues={initialValues} hideRequiredMark onFinish={this.onFinish}>
		      <FormItem {...layout} label="选择组织" rules={[{ required: true }]}>
		        <Card bordered={false} bodyStyle={{ padding: '0' }} >
		          <FormItem noStyle>
		            <Checkbox
		              style={{ lineHeight: '35px' }}
		              indeterminate={this.state.indeterminate}
		              onChange={this.onCheckAllChange}
		              checked={this.state.checkAll}
		            >
										全选
		            </Checkbox>
		          </FormItem>
		          <FormItem name="options" rules={[{ required: true, message: '请选择组织' }]} noStyle>
		            <CheckboxGroup style={{ width: '100%', background: '#ffffff' }} onChange={this.onChange} >
		              {orgList.map((item) => {
		                return (
		                  <Checkbox
		                    key={item.id}
		                    style={{ lineHeight: '35px' }}
		                    value={item.id}
		                  >
		                    {item.display_name}
		                  </Checkbox>
		                )
		              })}
		            </CheckboxGroup>
		          </FormItem>
		        </Card>
		      </FormItem>
		      <FormItem {...tailLayout} >
		        <Button type="primary" htmlType="submit">
									提交
		        </Button>
		        <Button style={{ marginLeft: 8 }} onClick={() => { this.props.history.goBack() }} disabled={this.state.cancelDisabled}>
									取消
		        </Button>
		      </FormItem>
		    </Form>
		  )
		}

		renderNoOrg = () => {
		  return (
		    <div className="invite-box empty">
		      <img width={112} src={require('@/images/fabric/1.svg')} alt="" />
		      <div className="empty-go">
		        <span>没有任何组织？请前往组织管理页面申请添加组织</span>
		      </div>
		    </div>
		  )
		}

		render() {
		  const { orgList, channelName, type } = this.state
		  return (
		    <Spin spinning={this.state.loading}>
		      <Card className="join-channel-box">
		        <h1 className="invite-title">{`请选择需要${type === 'APPLY' ? '申请' : '邀请'}加入通道"${channelName}"的组织`}</h1>
		        {
		          orgList.length ? this.renderForm() : this.renderNoOrg()
		        }
		      </Card>
		    </Spin>
		  )
		}
}

export default JoinChannel
